package rullekake.beans;

import java.util.LinkedList;
import rullekake.entities.StudyProgram;
import rullekake.beans.util.JsfUtil;
import rullekake.facade.StudyProgramFacade;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import rullekake.entities.Course;
import rullekake.entities.Faculty;

/**
 * Klasse som håndterer oppretting/visning/endring av studieprogram
 *
 */

@ManagedBean (name="studyProgramController")
@SessionScoped
public class StudyProgramController {

    private StudyProgram current;
    private DataModel items = null;
    @EJB private rullekake.facade.StudyProgramFacade ejbFacade;
    @EJB private rullekake.facade.CourseFacade ejbCourseFacade;

    public StudyProgramController() {
    }

    public StudyProgram getSelected() {
        if (current == null) {
            current = new StudyProgram();
        }
        return current;
    }

    private StudyProgramFacade getFacade() {
        return ejbFacade;
    }

    public String prepareList() {
        recreateModel();
        return "studyProgram/List";
    }

    public String prepareView() {
        current = (StudyProgram)getItems().getRowData();
        return "studyProgram/View";
    }

    public String prepareCreate() {
        current = new StudyProgram();
        return "studyProgram/Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage("StudyProgramCreated");
            return "studyProgram/View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage("PersistenceErrorOccured");
            return null;
        }
    }
    
    public DataModel<Course> getCoursesFromFaculty() {
        return new ListDataModel(ejbCourseFacade.findCoursesByFaculty(current.getFaculty()));
    }

    public DataModel<Course> getCourseFromInstitution() {
        LinkedList<Course> institutesCourses = new LinkedList<Course>();
        for (Faculty f: current.getFaculty().getInstitution().getFacultyCollection()) {
            institutesCourses.addAll(ejbCourseFacade.findCoursesByFaculty(f));
        }
        return new ListDataModel(institutesCourses);
    }

    public String prepareEdit() {
        current = (StudyProgram)getItems().getRowData();
        return "studyProgram/Edit";
    }

    public String update() {
        try {
            for (Course fromAll: getCourseFromInstitution()){
                for (Course fromChosen: current.getCourseCollection()) {
                    if (fromChosen.equals(fromAll) && !fromAll.getStudyProgramCollection().contains(current))
                    fromAll.getStudyProgramCollection().add(current);
                }
                if (!current.getCourseCollection().contains(fromAll) && fromAll.getStudyProgramCollection().contains(current)){
                    fromAll.getStudyProgramCollection().remove(current);
                }
                ejbCourseFacade.edit(fromAll);
            }
            getFacade().edit(current);
            JsfUtil.addSuccessMessage("StudyProgramUpdated");
            return "studyProgram/View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage("PersistenceErrorOccured");
            return null;
        }
    }

    public String destroy() {
        try {
            getFacade().remove(current);
        } catch (Exception e) {
            JsfUtil.addErrorMessage("PersistenceErrorOccured");
            return null;
        }
        recreateModel();
        return "studyProgram/List";
    }
    
    public DataModel getItems() {
        if (items == null) {
            items = new ListDataModel(getFacade().findAll());
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public void setStudyProgramsByFaculty(Faculty faculty) {
            items = new ListDataModel(getFacade().findStudyProgramsByFaculty(faculty));
    }

    @FacesConverter(forClass=StudyProgram.class)
    public static class StudyProgramControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            StudyProgramController controller = (StudyProgramController)facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "studyProgramController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof StudyProgram) {
                StudyProgram o = (StudyProgram) object;
                return getStringKey(o.getStudyProgramId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: "+StudyProgramController.class.getName());
            }
        }
    }
}